<template>
    <div class="border shadow col-6 mx-auto mt-3 p-3">
        <table class="table table-striped table-inverse">
            <thead class="thead-inverse">
                <tr>
                    <th></th>
                    <th>商品名称</th>
                    <th>商品单价</th>
                    <th>商品数量</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <template v-for="(item, index) in tableInfo">
                    <tr>
                        <td scope="row">{{ item.id }}</td>
                        <td>{{ item.name }}</td>
                        <td>{{ item.price }}</td>
                        <td><button type="button" class="btn btn-danger" @click="sub(index)">-</button>{{ item.count
                        }}<button type="button" class="btn btn-success" @click="add(index)">+</button></td>
                        <td><button type="button" class="btn btn-danger" @click="del(index)">移除</button></td>
                    </tr>
                </template>
            </tbody>
            <h3>总价：{{ priceTotal }}</h3>
        </table>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue';
const tableInfo = ref([
    { id: 1, name: "iphoneX", price: 7999, count: 1, },
    { id: 2, name: "荣耀16", price: 2399, count: 1, },
    { id: 3, name: "华为P22", price: 3399, count: 1, },
    { id: 4, name: "小米9", price: 3999, count: 1, },
]);
const priceTotal = computed({
    set(newValue) {
        tableInfo.value = newValue;
    },
    get() {
        return tableInfo.value.reduce((acc, item) => {
            return acc + item.count * item.price;
        }, 0)
    },
});
const sub = (index) => {
    if (!tableInfo.value[index].count == 0) {
        tableInfo.value[index].count--;
    }
}
const add = (index) => {
    tableInfo.value[index].count++;
}
const del = (index) => {
    tableInfo.value.forEach((item, i) => {
        if (index == i) {
            tableInfo.value.splice(i, 1);
        }
    })
}
</script>

<style lang="scss" scoped></style>